package ar.com.spsolutions.splibrary.repositories;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import ar.com.spsolutions.splibrary.book.Book;
import ar.com.spsolutions.splibrary.book.category.Category;

public class CategoryRepository extends HibernateGenericDAO<Category> implements
		GenericRepository<Category> {

	private static final long serialVersionUID = -5010926405340660049L;
	private static final String NAME_PROPERTY = "name";
	private static final String UNCHECKED = "unchecked";

	public CategoryRepository() {
		super(Category.class);
	}

	public boolean exist(final Category category) {
		return !(this.findByName(category.getName()) == null);
	}

	public Category findByName(final String name) {
		return this.findByEq("name", name);
	}

	public int sizeOfSearch(final String searchValue) {
		final DetachedCriteria criteria = this.createDetachableCriteria();
		criteria.add(Restrictions.ilike(CategoryRepository.NAME_PROPERTY,
				searchValue, MatchMode.ANYWHERE));
		return this.getHibernateTemplate().findByCriteria(criteria).size();
	}

	@SuppressWarnings(CategoryRepository.UNCHECKED)
	public List<? extends Category> getResults(final String searchValue,
			final int first, final int count) {
		final DetachedCriteria criteria = this.createDetachableCriteria();
		criteria.add(Restrictions.ilike(CategoryRepository.NAME_PROPERTY,
				searchValue, MatchMode.ANYWHERE));
		return this.getHibernateTemplate().findByCriteria(criteria, first,
				count);
	}

	public List<Book> getBooksFor(final Category category) {
		final Category retrived = this.findByEq("name", category.getName());
		return new ArrayList<Book>(retrived.getBooks());
	}

}
